<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class Cate extends Model
{
    // 表名
    public $table = 'category';

    // 主键
    public $primaryKey = 'cate_id';

    // 是否允许批量操作
//    public $fillable = ['uername','password','salt'];
    // 不允许批量操作
    public $guarded = [];

    // 是否维护created_at和updated_at字段
    public $timestamps = false;

    // 获取分类数据
    public function tree($request)
    {
        $cates = $this->orderBy('cate_order','asc')
            ->where(function($query) use($request){
                $cate_name = $request->input('cate_name');
                if(!empty($cate_name)){
                    $query->where('cate_name','like','%'. $cate_name .'%');
                }
            })
            ->paginate($request->input('num') ? $request->input('num') : 50);
//        $cates = $this->orderBy('cate_order','asc')->get()->toArray();

        // 格式化，排序（二级分类缩进）
        return $this->getTree($cates);
    }

    public function getTree($category)
    {
        // 存放最终排序分类完的数据
//        $category->arr = collect([]);
        $arr = [];
        foreach ($category as $k=>$v){
            // 一级分类
            if($v->cate_pid == 0){
                $arr[] = $v;
                // 二级分类
                foreach ($category as $m=>$n){
                    if($v->cate_id == $n->cate_pid){
                        // 缩进
                        $n->cate_name = '|-----' . $n->cate_name;
                        $arr[] = $n;
                    }
                }
            }
        }

        return $arr;

    }
}
